package com.songcha.module_splash.ui.activity.splash


import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.os.Debug
import android.os.Handler
import android.os.Looper
import android.text.Spannable
import android.text.SpannableString
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.ViewModel
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.library_base.base.BaseActivity
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.api.MyInterceptor
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.AdvertHelper.ICSJSplashAdListener
import com.songcha.library_business.helper.AdvertHelper.ITTAdSdkCallback
import com.songcha.library_business.helper.WxHelper
import com.songcha.library_business.proxy.configuration.SystemConfigurationManager
import com.songcha.library_business.proxy.teenager.TeenagerManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.ui.view.CustomButton
import com.songcha.library_common.util.*
import com.songcha.module_splash.BuildConfig
import com.songcha.module_splash.R
import com.songcha.module_splash.databinding.SplashActivitySplashBinding
import com.songcha.module_splash.ui.dialog.UserPrivacyDialog
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.jessyan.autosize.AutoSize
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.internal.CancelAdapt
import org.greenrobot.greendao.annotation.ToMany
import java.lang.ref.WeakReference
import java.lang.reflect.ParameterizedType
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

/*class SplashActivity:BaseMvvmActivity<SplashViewModel,SplashActivitySplashBinding>(){
    override fun getLayoutId(): Int {
        return R.layout.splash_activity_splash
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        try{
            ToastUtil.show(this.javaClass.genericSuperclass is ParameterizedType)
            val cls=(this.javaClass.genericSuperclass as ParameterizedType)
        }catch (e:Exception){
            e.printStackTrace()
            ToastUtil.show(e.message)
        }

        //super.initOnCreate(savedInstanceState)
    }
}*/


@Route(path = "/splash/SplashActivity")
//avoid splash window background scale,so implement CancelAdapt
class SplashActivity : BaseMvvmActivity<SplashViewModel,SplashActivitySplashBinding>(),CancelAdapt{
    private var mSkipDispose: Disposable? = null
    private var mIsFirstOpen = true
    private var mIsAgreeUserPolicy = false
    private var mIsShowAdvert = false
    private var mIsAdvertInitError = false


    override fun getLayoutId(): Int {
        return R.layout.splash_activity_splash
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun initOnCreate(savedInstanceState: Bundle?) {
        installSplashScreen()
        super.initOnCreate(savedInstanceState)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        StatusBarUtil.fullScreen(this)

        //mFlParent=findViewById(R.id.splash_fl_parent)
        mIsAgreeUserPolicy= SharedPreferenceHelper.getInt("splash","isAgreen")==1
        mIsFirstOpen=!mIsAgreeUserPolicy
        if(!mIsAgreeUserPolicy){
            AutoSize.autoConvertDensityOfGlobal(this)
            val dialog = UserPrivacyDialog(this@SplashActivity){
                mIsAgreeUserPolicy=true
                initializeApp()
            }
            dialog.show()
        }else{
            initializeApp()
        }

        databinding.includeSplash.splashCclSkipCountdown.setOnClickListener{v->
            if(mIsAgreeUserPolicy)
                toMain()
        }

        viewModel.skipCountDown.observe(this){data->
            databinding.includeSplash.splashTvSkipCountdown.text="跳过 $data"
            if(data==0 && mIsAgreeUserPolicy){
                toMain()
            }
        }


        viewModel.advertState.observe(this){data->
            if(data){
                initAdvertSdk()
            }else{
                toMain()
            }

        }

    }

    private fun initAdvertSdk(){

        fun onInitAdvertSuccess(){
            //if(mIsFirstOpen || !isShowAdvert)
            showSplashAdvert()
        }

        fun onInitAdvertFail(){
            mIsAdvertInitError = true
            toMain()
        }

        AdvertHelper.initAdvert(this,VarConfig.ADVERT_APP_ID_CSJ,object:ITTAdSdkCallback<SplashActivity>{
            override fun onSuccess(activity: SplashActivity) {

                AdvertHelper.initAdvert_GDT(this@SplashActivity,VarConfig.ADVERT_APP_ID_GDT,object:AdvertHelper.GDTAdSdkOnStartListener{
                    override fun onSuccess() {
                        onInitAdvertSuccess()
                    }

                    override fun onError(code: Int, msg: String) {
                        onInitAdvertFail()
                    }

                })

            }

            override fun onFail(activity: SplashActivity, po: Int, p1: String) {
                onInitAdvertFail()
            }
        })
    }

    //agree privacy policy and init
    private fun initializeApp(){
        MyInterceptor.getInstance().setAccessDeviceEnabled(true)

        WxHelper.initWxApi(application, application.resources.getString(com.songcha.library_business.R.string.wx_appid))

        val channel=PackageUtil.getUmengChannelName(LibraryCommon.getContext())
        //bugly
        if(!BuildConfig.DEBUG){
            val strategy = CrashReport.UserStrategy(LibraryCommon.getContext())
            strategy.appChannel=channel
            strategy.deviceModel=DeviceUtil.getDeviceName()
            CrashReport.initCrashReport(this, resources.getString(R.string.bugly_appid), BuildConfig.DEBUG,strategy)
        }

        //umeng
        UMConfigure.init(this,resources.getString(R.string.umeng_appkey),channel,UMConfigure.DEVICE_TYPE_PHONE,"")
        //app start
        if(UserInfoManager.checkLogin()){
            viewModel.updateClientIp()
            viewModel.getUserInfo()
        }

        viewModel.getSystemConfiguration()

    }

    private fun showSplashAdvert(){
        if(isFinishing) return

        mIsShowAdvert = true
        AdvertCoverHelper.loadAdvertByCover(this,AdvertHelper.ADVERT_TYPE_SPLASH,VarConfig.ADVERT_SPLASH_INFO,
            null,0f,
            object:AdvertHelper.ILoadAdvertCommonListener{
            override fun onSuccess(type: Int, height: Int,view:View?) {
                if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                    if (!isFinishing) {
                        databinding.includeSplash.splashFlAdvert.layoutParams =  databinding.includeSplash.splashFlAdvert.layoutParams.apply {
                            this.height = height
                        }

                        databinding.includeSplash.splashFlAdvert.removeAllViews()
                        //pay attention to:spalsh advert width must equal screenwidth,height must greater than 75% screenheight
                        AdvertHelper.showSplashView(databinding.includeSplash.splashFlAdvert)
                        //hide skip button and custom by yourself
                        AdvertHelper.hideSkipButton()

                        databinding.includeSplash.splashCclSkipCountdown.visibility = View.VISIBLE
                        mSkipDispose = Observable.intervalRange(0,4,0,1, TimeUnit.SECONDS)
                            .subscribeOn(Schedulers.computation())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe{
                                viewModel.setCountDown(3 - it.toInt())
                            }
                    }else {
                        //handle jump to main logic
                        toMain()
                    }
                }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){
                    if (!isFinishing) {
                        val lp = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,height)
                        databinding.includeSplash.splashFlAdvert.layoutParams = lp
                        databinding.includeSplash.splashFlAdvert.removeAllViews()
                        AdvertHelper.showSplashAd_GDT(databinding.includeSplash.splashFlAdvert)
                    }else{
                        toMain()
                    }
                }
            }

            override fun onError(type: Int,code:Int,msg:String) {
                toMain()
            }

            override fun onClose(type: Int) {
                if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                    toMain()
                }else if(type == AdvertInfoBean.ADVERT_TYPE_GDT){
                    if(mForceGoMain && mIsAgreeUserPolicy && mIsShowAdvert && !mIsAdvertInitError)
                        toMain()
                    else
                        mForceGoMain = true
                }
            }

        })

    }

    private var mForceGoMain=false

    override fun onPause() {
        super.onPause()
        mForceGoMain = false
    }

    override fun onResume() {
        super.onResume()
        //if(mForceGoMain && mIsAgreeUserPolicy && mIsShowAdvert && !mIsAdvertInitError){
            //toMain()
        //}
        if(mForceGoMain && mIsAgreeUserPolicy && mIsShowAdvert && !mIsAdvertInitError){
            toMain()
        }
        mForceGoMain = true
    }

    private fun toMain(){
        //return
        if(TeenagerManager.isTeenagerMode){
            ARouter.getInstance().build("/mine/TeenagerModeActivity").navigation()
        }else{
            ARouter.getInstance().build("/main/MainActivity").navigation()
        }
        //avoid finish before main activity
        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        },200)
    }

    override fun onDestroy() {
        super.onDestroy()
        //mAd?.setSplashAdListener(null)
        AdvertHelper.destroy()
        mSkipDispose?.dispose()
        databinding.includeSplash.splashFlAdvert.removeAllViews()
    }

}
